/**
 * Author: luoqi
 * Created Date: 2025-08-24 02:21:50
 * Last Modified: 2025-08-24 02:21:50
 * Modified By: luoqi at <**@****>
 * Copyright (c) 2025 <*****>
 * Description:
 */

#include <string.h>
#include "utils.h"

bool is_hex_str(const char *hex_str)
{
    if(!hex_str) {
        return false;
    }

    int len = strlen(hex_str);

    if(len >= 2 &&
        ((hex_str[0] == '0' && hex_str[1] == 'x') ||
            (hex_str[0] == '0' && hex_str[1] == 'X'))) {
        hex_str += 2;
        len -= 2;
    }

    if(len == 0) {
        return false;
    }

    for(int i = 0; i < len; i++) {
        char c = hex_str[i];
        if((c < '0' || c > '9') &&
            (c < 'a' || c > 'f') &&
            (c < 'A' || c > 'F')) {
            return false;
        }
    }

    return true;
}

uint32_t hex_str_to_uint32(const char *hex_str)
{
    uint32_t result = 0;
    int i = 0;
    int len = strlen(hex_str);

    if(len >= 2 &&
        ((hex_str[0] == '0' && hex_str[1] == 'x') ||
            (hex_str[0] == '0' && hex_str[1] == 'X'))) {
        i = 2;
    }

    for(; i < len; i++) {
        char c = hex_str[i];
        uint8_t val;

        if(c >= '0' && c <= '9') {
            val = c - '0';
        } else if(c >= 'a' && c <= 'f') {
            val = 10 + (c - 'a');
        } else if(c >= 'A' && c <= 'F') {
            val = 10 + (c - 'A');
        } else {
            return result;
        }

        result = (result << 4) | val;
    }

    return result;
}


